﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfStudy
{
    /// <summary>
    /// MyRoutedEvent.xaml 的交互逻辑
    /// </summary>
    public partial class MyRoutedEvent : Window
    {

        private RoutedCommand cmd = new RoutedCommand("Move",typeof(MyRoutedEvent));

        public MyRoutedEvent()
        {
            InitializeComponent();

            //InitButtonCmd();

            //添加路由事件
            //GridRoot.AddHandler(Button.ClickEvent, new RoutedEventHandler(ButtonClicked));
        }

        private void ButtonClicked(object sender, RoutedEventArgs e)
        {
            //sender是响应监听事件的控件本身，e可以找到事件响应源OriginalSource
            //MessageBox.Show((e.OriginalSource as FrameworkElement).Name);
            if ("RightButton".Equals((e.OriginalSource as FrameworkElement).Name) && (double)backBoder.RenderTransform.GetValue(TranslateTransform.XProperty)==0
                || "LeftButton".Equals((e.OriginalSource as FrameworkElement).Name) && (double)backBoder.RenderTransform.GetValue(TranslateTransform.XProperty) !=0 )
            {
                doAnimation();
            }
            
        }

        private void InitButtonCmd()
        {
            LeftButton.Command = cmd;
            RightButton.Command = cmd;

            //指定命令目标
            LeftButton.CommandTarget = backBoder;
            RightButton.CommandTarget = backBoder;

            //创建命令关联
            CommandBinding cd = new CommandBinding();
            cd.Command = cmd;
            cd.CanExecute += new CanExecuteRoutedEventHandler(Cd_CanExecute);
            cd.Executed += new ExecutedRoutedEventHandler(Cd_Executed);

            GridA.CommandBindings.Add(cd);
        }

        private void Cd_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            doAnimation();
        }

        private void Cd_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            MessageBox.Show((e.Source as FrameworkElement).Name);
            e.Handled = true;
        }

        private void doAnimation()
        {
            DoubleAnimation dx = new DoubleAnimation();
            if (tt.X==0)
            {
                dx.To = (GridA.ActualWidth - backBoder.Width);
            }
            else
            {
                dx.To = 0;
            }

            CubicEase cubicEase = new CubicEase() { EasingMode = EasingMode.EaseOut };
            dx.EasingFunction = cubicEase;

            Duration duration = new Duration(TimeSpan.FromSeconds(1));
            dx.Duration = duration;

            tt.BeginAnimation(TranslateTransform.XProperty, dx);
        }
    }
}
